//
//  ProfileEditViewModel.swift
//  App_Profile
//
//  Created by 蒋晨成 on 2022/1/18.
//

import Base
import Center
import Foundation
import RxCocoa
import RxSwift
import UIKit

class ProfileEditViewModel: ViewModel {
    let avatarSelected = PublishSubject<Void>()
    let reloadData = PublishSubject<Void>()
    let route = PublishSubject<String>()

    override init() {
        super.init()
        UserCenter.appendProfileChangeHandler(handler: self)
        refreshItems()
    }

    deinit {
        UserCenter.removeProfileChangeHandler(handler: self)
    }

    var items = [[RYBaseCellModel]]()
}

private extension ProfileEditViewModel {
    func refreshItems() {
        items = getItems()
    }

    func getItems() -> [[RYBaseCellModel]] {
        let avatarCellModel = RYAvatarCellModel(
            title: ProfileModular.localizedString(key: "Profile.Userinfo.Avatar"),
            imageUrl: UserCenter.userInfo?.avatar.url,
            placeHolder: ProfileModular.image(named: "Common.Avatar.Placeholder")
        ) { [weak self] _ in
            self?.avatarSelected.onNext(())
        }

        let nickNameCellModel = RYTextCellModel(title: ProfileModular.localizedString(key: "Profile.Userinfo.Username"),
                                                text: UserCenter.userInfo?.username) { [weak self] _ in
            let pattern = "profile/edit/username".urlEncode()
            self?.route.onNext("/show/push/\(pattern)")
        }

        let male = ProfileModular.localizedString(key: "Profile.Userinfo.Gender.Male")
        let female = ProfileModular.localizedString(key: "Profile.Userinfo.Gender.Female")

        let genderCellModel = RYTextCellModel(title: ProfileModular.localizedString(key: "Profile.Userinfo.Gender"),
                                              text: UserCenter.userInfo?.gender == 1 ? male : female) { [weak self] _ in
            let pattern = "profile/edit/gender".urlEncode()
            self?.route.onNext("/show/present/\(pattern)")
        }

        let signatureCellModel = RYTextCellModel(title: ProfileModular.localizedString(key: "Profile.Userinfo.Signature"), text: UserCenter.userInfo?.signature) { [weak self] _ in
            let pattern = "profile/edit/signature".urlEncode()
            self?.route.onNext("/show/push/\(pattern)")
        }

        let securityCellModel = RYTitleCellModel(title: ProfileModular.localizedString(key: "Profile.Userinfo.Security")) { [weak self] _ in
            let pattern = "profile/edit/security".urlEncode()
            self?.route.onNext("/show/push/\(pattern)")
        }

        return [[avatarCellModel, nickNameCellModel, genderCellModel, signatureCellModel, securityCellModel]]
    }
}

extension ProfileEditViewModel: UserCenterProfileChangeProtocol {
    func userProfileDidChange() {
        refreshItems()
        reloadData.onNext(())
    }
}
